<template>
  <div class="admin-media">
    <div class="page-header">
      <h2>媒体管理</h2>
      <!-- <div class="header-actions">
        <el-button @click="handlePreview">
          <el-icon><View /></el-icon>
          预览效果
        </el-button>
      </div> -->
    </div>

    <!-- 内容管理标签页 -->
    <el-tabs v-model="activeTab" type="border-card" class="content-tabs">
      <!-- 展会资讯 -->
      <el-tab-pane label="展会资讯" name="exhibition-news">
        <div class="tab-content">
          <div class="list-header">
            <h3>展会资讯列表</h3>
            <div class="header-actions">
              <el-input
                v-model="searchText"
                placeholder="搜索标题或描述..."
                style="width: 200px; margin-right: 10px"
                clearable
                @input="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-select
                v-model="statusFilter"
                placeholder="状态筛选"
                style="width: 120px; margin-right: 10px"
                clearable
                @change="handleFilter"
              >
                <el-option label="已发布" value="active" />
                <el-option label="草稿" value="inactive" />
              </el-select>
              <el-button
                type="primary"
                size="small"
                @click="showAddDialog('exhibition-news', 'news')"
              >
                <el-icon><Plus /></el-icon>
                新增展会资讯
              </el-button>
            </div>
          </div>

          <el-table
            :data="getPageList('exhibition-news')"
            v-loading="loading"
            stripe
          >
            <el-table-column prop="title" label="标题" />
            <!-- <el-table-column prop="subtitle" label="副标题" min-width="150">
              <template #default="scope">
                {{ getContentField(scope.row, "subtitle") }}
              </template>
            </el-table-column> -->
            <el-table-column prop="content" label="内容">
              <template #default="scope">
                <span
                  class="content-preview"
                  @click="previewContent(scope.row)"
                  :title="stripHtml(getContentField(scope.row, 'content'))"
                >
                  {{
                    stripHtml(getContentField(scope.row, "content")).substring(
                      0,
                      20
                    )
                  }}{{
                    stripHtml(getContentField(scope.row, "content")).length > 20
                      ? "..."
                      : ""
                  }}
                </span>
              </template>
            </el-table-column>

            <el-table-column prop="linkUrl" label="外部链接">
              <template #default="scope">
                <el-link
                  v-if="scope.row.linkUrl"
                  :href="scope.row.linkUrl"
                  target="_blank"
                  type="primary"
                >
                  查看链接
                </el-link>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="sortOrder" label="排序" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag
                  :type="scope.row.status === 'active' ? 'success' : 'info'"
                >
                  {{ scope.row.status === "active" ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="创建时间" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="editPageItem(scope.row, 'news')"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  @click="deletePageItem(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 媒体报道 -->
      <el-tab-pane label="媒体报道" name="media-reports">
        <div class="tab-content">
          <div class="list-header">
            <h3>媒体报道列表</h3>
            <div class="header-actions">
              <el-input
                v-model="searchText"
                placeholder="搜索标题或描述..."
                style="width: 200px; margin-right: 10px"
                clearable
                @input="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-select
                v-model="statusFilter"
                placeholder="状态筛选"
                style="width: 120px; margin-right: 10px"
                clearable
                @change="handleFilter"
              >
                <el-option label="已发布" value="active" />
                <el-option label="草稿" value="inactive" />
              </el-select>
              <el-button
                type="primary"
                size="small"
                @click="showAddDialog('media-reports', 'report')"
              >
                <el-icon><Plus /></el-icon>
                新增媒体报道
              </el-button>
            </div>
          </div>

          <el-table
            :data="getPageList('media-reports')"
            v-loading="loading"
            stripe
          >
            <el-table-column prop="title" label="标题" />
            <!-- <el-table-column prop="subtitle" label="副标题" min-width="150">
              <template #default="scope">
                {{ getContentField(scope.row, "subtitle") }}
              </template>
            </el-table-column> -->
            <el-table-column prop="content" label="内容">
              <template #default="scope">
                <span
                  class="content-preview"
                  @click="previewContent(scope.row)"
                  :title="stripHtml(getContentField(scope.row, 'content'))"
                >
                  {{
                    stripHtml(getContentField(scope.row, "content")).substring(
                      0,
                      20
                    )
                  }}{{
                    stripHtml(getContentField(scope.row, "content")).length > 20
                      ? "..."
                      : ""
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="linkUrl" label="外部链接">
              <template #default="scope">
                <el-link
                  v-if="scope.row.linkUrl"
                  :href="scope.row.linkUrl"
                  target="_blank"
                  type="primary"
                >
                  查看链接
                </el-link>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="sortOrder" label="排序" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag
                  :type="scope.row.status === 'active' ? 'success' : 'info'"
                >
                  {{ scope.row.status === "active" ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="创建时间" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button
                  size="small"
                  @click="editPageItem(scope.row, 'report')"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  @click="deletePageItem(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 行业资讯 -->
      <el-tab-pane label="行业资讯" name="industry-news">
        <div class="tab-content">
          <div class="list-header">
            <h3>行业资讯列表</h3>
            <div class="header-actions">
              <el-input
                v-model="searchText"
                placeholder="搜索标题或描述..."
                style="width: 200px; margin-right: 10px"
                clearable
                @input="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-select
                v-model="statusFilter"
                placeholder="状态筛选"
                style="width: 120px; margin-right: 10px"
                clearable
                @change="handleFilter"
              >
                <el-option label="已发布" value="active" />
                <el-option label="草稿" value="inactive" />
              </el-select>
              <el-button
                type="primary"
                size="small"
                @click="showAddDialog('industry-news', 'news')"
              >
                <el-icon><Plus /></el-icon>
                新增行业资讯
              </el-button>
            </div>
          </div>

          <el-table
            :data="getPageList('industry-news')"
            v-loading="loading"
            stripe
          >
            <el-table-column prop="title" label="标题" />
            <!-- <el-table-column prop="subtitle" label="副标题" min-width="150">
              <template #default="scope">
                {{ getContentField(scope.row, "subtitle") }}
              </template>
            </el-table-column> -->
            <el-table-column prop="content" label="内容">
              <template #default="scope">
                <span
                  class="content-preview"
                  @click="previewContent(scope.row)"
                  :title="stripHtml(getContentField(scope.row, 'content'))"
                >
                  {{
                    stripHtml(getContentField(scope.row, "content")).substring(
                      0,
                      20
                    )
                  }}{{
                    stripHtml(getContentField(scope.row, "content")).length > 20
                      ? "..."
                      : ""
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="linkUrl" label="外部链接">
              <template #default="scope">
                <el-link
                  v-if="scope.row.linkUrl"
                  :href="scope.row.linkUrl"
                  target="_blank"
                  type="primary"
                >
                  查看链接
                </el-link>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="sortOrder" label="排序" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag
                  :type="scope.row.status === 'active' ? 'success' : 'info'"
                >
                  {{ scope.row.status === "active" ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="创建时间" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="editPageItem(scope.row, 'news')"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  @click="deletePageItem(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 现场集锦 -->
      <el-tab-pane label="现场集锦" name="on-site-highlights">
        <div class="tab-content">
          <div class="list-header">
            <h3>现场集锦列表</h3>
            <div class="header-actions">
              <el-input
                v-model="searchText"
                placeholder="搜索标题或描述..."
                style="width: 200px; margin-right: 10px"
                clearable
                @input="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-select
                v-model="statusFilter"
                placeholder="状态筛选"
                style="width: 120px; margin-right: 10px"
                clearable
                @change="handleFilter"
              >
                <el-option label="已发布" value="active" />
                <el-option label="草稿" value="inactive" />
              </el-select>
              <el-button
                type="primary"
                size="small"
                @click="showAddDialog('on-site-highlights', 'highlight')"
              >
                <el-icon><Plus /></el-icon>
                新增现场集锦
              </el-button>
            </div>
          </div>

          <el-table
            :data="getPageList('on-site-highlights')"
            v-loading="loading"
            stripe
          >
            <el-table-column prop="title" label="标题" />
            <!-- <el-table-column prop="subtitle" label="副标题" min-width="150">
              <template #default="scope">
                {{ getContentField(scope.row, "subtitle") }}
              </template>
            </el-table-column> -->
            <el-table-column prop="content" label="内容">
              <template #default="scope">
                <span
                  class="content-preview"
                  @click="previewContent(scope.row)"
                  :title="stripHtml(getContentField(scope.row, 'content'))"
                >
                  {{
                    stripHtml(getContentField(scope.row, "content")).substring(
                      0,
                      20
                    )
                  }}{{
                    stripHtml(getContentField(scope.row, "content")).length > 20
                      ? "..."
                      : ""
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="imageUrl" label="主图片">
              <template #default="scope">
                <div class="image-container" @click="previewImages(scope.row)">
                  <img
                    v-if="scope.row.imageUrl"
                    :src="scope.row.imageUrl"
                    class="table-image"
                  />
                  <span v-else class="no-image">无图片</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="linkUrl" label="外部链接">
              <template #default="scope">
                <el-link
                  v-if="scope.row.linkUrl"
                  :href="scope.row.linkUrl"
                  target="_blank"
                  type="primary"
                >
                  查看链接
                </el-link>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="sortOrder" label="排序" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag
                  :type="scope.row.status === 'active' ? 'success' : 'info'"
                >
                  {{ scope.row.status === "active" ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="创建时间" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button
                  size="small"
                  @click="editPageItem(scope.row, 'highlight')"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  @click="deletePageItem(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 合作媒体 -->
      <el-tab-pane label="合作媒体" name="cooperative-media">
        <div class="tab-content">
          <div class="list-header">
            <h3>合作媒体列表</h3>
            <div class="header-actions">
              <el-button
                type="success"
                size="small"
                @click="downloadCooperativeMediaTemplate"
              >
                <el-icon><Download /></el-icon>
                下载模板
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="triggerCooperativeMediaImport"
              >
                <el-icon><Upload /></el-icon>
                批量导入
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="addCooperativeMedia"
              >
                <el-icon><Plus /></el-icon>
                新增合作媒体
              </el-button>
            </div>
          </div>

          <!-- 隐藏的文件上传输入框 -->
          <input
            ref="cooperativeMediaImportRef"
            type="file"
            accept=".csv,.xlsx,.xls"
            style="display: none"
            @change="handleCooperativeMediaImport"
          />

          <!-- 查询条件 -->
          <el-form
            :model="cooperativeMediaQueryForm"
            label-width="120px"
            class="query-form"
          >
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="媒体名称">
                  <el-input
                    v-model="cooperativeMediaQueryForm.name"
                    placeholder="请输入媒体名称"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="媒体类型">
                  <el-select
                    v-model="cooperativeMediaQueryForm.type"
                    placeholder="请选择媒体类型"
                    clearable
                  >
                    <el-option label="报纸" value="newspaper" />
                    <el-option label="杂志" value="magazine" />
                    <el-option label="网络媒体" value="online" />
                    <el-option label="电视" value="tv" />
                    <el-option label="广播" value="radio" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="状态">
                  <el-select
                    v-model="cooperativeMediaQueryForm.status"
                    placeholder="请选择状态"
                    clearable
                  >
                    <el-option label="启用" value="active" />
                    <el-option label="禁用" value="inactive" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item>
                  <el-button type="primary" @click="searchCooperativeMediaData"
                    >查询</el-button
                  >
                  <el-button @click="resetCooperativeMediaQuery"
                    >重置</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <el-table
            :data="filteredCooperativeMediaData"
            v-loading="loading"
            stripe
          >
            <el-table-column prop="title" label="媒体名称" width="150" />
            <el-table-column label="媒体Logo" width="120">
              <template #default="scope">
                <div class="image-container" @click="previewImages(scope.row)">
                  <img
                    v-if="scope.row.imageUrl"
                    :src="scope.row.imageUrl"
                    class="table-image"
                  />
                  <span v-else class="no-image">无Logo</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="媒体类型" width="100">
              <template #default="scope">
                {{ getContentField(scope.row, "type") || "-" }}
              </template>
            </el-table-column>
            <el-table-column prop="content" label="媒体描述" min-width="200">
              <template #default="scope">
                <span
                  class="content-preview"
                  @click="previewContent(scope.row)"
                  :title="stripHtml(getContentField(scope.row, 'description'))"
                >
                  {{
                    stripHtml(
                      getContentField(scope.row, "description")
                    ).substring(0, 30)
                  }}{{
                    stripHtml(getContentField(scope.row, "description"))
                      .length > 30
                      ? "..."
                      : ""
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="官网链接" width="100">
              <template #default="scope">
                <el-link
                  v-if="scope.row.linkUrl"
                  :href="scope.row.linkUrl"
                  target="_blank"
                  type="primary"
                >
                  访问官网
                </el-link>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="sortOrder" label="排序" width="80" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag
                  :type="scope.row.status === 'active' ? 'success' : 'info'"
                >
                  {{ scope.row.status === "active" ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="创建时间" width="150" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row, $index }">
                <div class="action-buttons">
                  <el-button size="small" @click="editCooperativeMedia(row)">
                    编辑
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteCooperativeMedia($index)"
                  >
                    删除
                  </el-button>
                  <el-button
                    size="small"
                    :type="row.status === 'active' ? 'warning' : 'success'"
                    @click="toggleCooperativeMediaStatus(row)"
                  >
                    {{ row.status === "active" ? "禁用" : "启用" }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 轮播图管理 -->
      <el-tab-pane label="轮播图管理" name="carousel">
        <div class="tab-content">
          <CarouselManager title="媒体中心轮播图管理" module-type="media" />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="dialogTitle"
      width="70%"
      :before-close="handleCloseEditDialog"
      class="edit-dialog"
    >
      <div class="edit-content">
        <el-form
          :model="editForm"
          label-width="120px"
          :rules="editRules"
          ref="editFormRef"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                :label="
                  tag == 'news'
                    ? '资讯标题'
                    : tag == 'report'
                    ? '报道标题'
                    : '集锦标题'
                "
                prop="title"
              >
                <el-input
                  v-model="editForm.title"
                  :placeholder="
                    tag == 'news'
                      ? '请输入资讯标题'
                      : tag == 'report'
                      ? '请输入报道标题'
                      : '请输入集锦标题'
                  "
                  maxlength="100"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="
                  tag == 'news'
                    ? '资讯类型'
                    : tag == 'report'
                    ? '报道类型'
                    : '集锦类型'
                "
                prop="pageType"
              >
                <el-select
                  v-model="editForm.pageType"
                  :placeholder="
                    tag == 'news'
                      ? '请选择资讯类型'
                      : tag == 'report'
                      ? '请选择报道类型'
                      : '请选择集锦类型'
                  "
                  style="width: 100%"
                >
                  <el-option label="展会资讯" value="exhibition-news" />
                  <el-option label="媒体报道" value="media-reports" />
                  <el-option label="行业资讯" value="industry-news" />
                  <el-option label="现场集锦" value="on-site-highlights" />
                  <el-option label="合作媒体" value="cooperative-media" />
                  <el-option label="媒体注册" value="media-registration" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- <el-form-item
            :label="
              tag == 'news'
                ? '资讯副标题'
                : tag == 'report'
                ? '报道副标题'
                : '集锦副标题'
            "
            prop="subtitle"
          >
            <el-input
              v-model="editForm.subtitle"
              :placeholder="
                tag == 'news'
                  ? '请输入资讯副标题（可选）'
                  : tag == 'report'
                  ? '请输入报道副标题（可选）'
                  : '请输入集锦副标题（可选）'
              "
              maxlength="200"
              show-word-limit
            />
          </el-form-item> -->

          <el-form-item
            :label="
              tag == 'news'
                ? '资讯描述'
                : tag == 'report'
                ? '报道描述'
                : '集锦描述'
            "
            prop="description"
          >
            <el-input
              v-model="editForm.description"
              type="textarea"
              :rows="3"
              :placeholder="
                tag == 'news'
                  ? '请输入资讯描述（可选）'
                  : tag == 'report'
                  ? '请输入报道描述（可选）'
                  : '请输入集锦描述（可选）'
              "
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item
            :label="
              tag == 'news'
                ? '资讯内容'
                : tag == 'report'
                ? '报道内容'
                : '集锦内容'
            "
            prop="content"
          >
            <RichTextEditor v-model="editForm.content" />
          </el-form-item>

          <el-row :gutter="20" v-if="tag == 'highlight'">
            <el-col :span="12">
              <el-form-item
                :label="
                  tag == 'news'
                    ? '资讯图片'
                    : tag == 'report'
                    ? '报道图片'
                    : '集锦图片'
                "
                prop="imageUrl"
              >
                <div class="image-upload-container">
                  <el-upload
                    class="image-uploader"
                    :action="uploadAction"
                    :headers="uploadHeaders"
                    :data="{ type: 'subpage' }"
                    :show-file-list="false"
                    :on-success="
                      (response) => handleImageSuccess(response, 'imageUrl')
                    "
                    :before-upload="beforeImageUpload"
                    accept="image/*"
                  >
                    <img
                      v-if="editForm.imageUrl"
                      :src="editForm.imageUrl"
                      class="uploaded-image"
                    />
                    <el-icon v-else class="image-uploader-icon"
                      ><Plus
                    /></el-icon>
                  </el-upload>
                  <el-input
                    v-model="editForm.imageUrl"
                    placeholder="或直接输入图片URL"
                    style="margin-top: 10px"
                  />
                </div>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="背景图片">
                <div class="image-upload-container">
                  <el-upload
                    class="image-uploader"
                    :action="uploadAction"
                    :headers="uploadHeaders"
                    :data="{ type: 'subpage' }"
                    :show-file-list="false"
                    :on-success="
                      (response) =>
                        handleImageSuccess(response, 'backgroundImage')
                    "
                    :before-upload="beforeImageUpload"
                    accept="image/*"
                  >
                    <img
                      v-if="editForm.backgroundImage"
                      :src="editForm.backgroundImage"
                      class="uploaded-image"
                    />
                    <el-icon v-else class="image-uploader-icon"
                      ><Plus
                    /></el-icon>
                  </el-upload>
                  <el-input
                    v-model="editForm.backgroundImage"
                    placeholder="或直接输入背景图片URL"
                    style="margin-top: 10px"
                  />
                </div>
              </el-form-item>
            </el-col> -->
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="链接地址">
                <el-input
                  v-model="editForm.linkUrl"
                  placeholder="请输入链接地址（可选）"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="排序">
                <el-input-number
                  v-model="editForm.sortOrder"
                  :min="0"
                  :max="999"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态">
                <el-radio-group v-model="editForm.status">
                  <el-radio label="active">启用</el-radio>
                  <el-radio label="inactive">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="info" @click="resetForm">重置</el-button>
          <!-- <el-button type="success" @click="previewPage">预览页面</el-button> -->
          <el-button type="primary" @click="savePageContent" :loading="saving"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 合作媒体编辑对话框 -->
    <el-dialog
      v-model="cooperativeMediaDialogVisible"
      :title="cooperativeMediaDialogTitle"
      width="600px"
    >
      <el-form :model="cooperativeMediaForm" label-width="100px">
        <el-form-item label="媒体名称" required>
          <el-input
            v-model="cooperativeMediaForm.name"
            placeholder="请输入媒体名称"
          />
        </el-form-item>

        <el-form-item label="媒体Logo">
          <div class="image-upload-container">
            <el-upload
              class="image-uploader"
              :action="uploadAction"
              :headers="uploadHeaders"
              :data="{ type: 'cooperative-media' }"
              :show-file-list="false"
              :on-success="
                (response) =>
                  handleCooperativeMediaImageSuccess(response, 'logo')
              "
              :before-upload="beforeImageUpload"
              accept="image/*"
            >
              <img
                v-if="cooperativeMediaForm.logo"
                :src="cooperativeMediaForm.logo"
                class="uploaded-image"
              />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <el-input
              v-model="cooperativeMediaForm.logo"
              placeholder="或直接输入Logo URL"
              style="margin-top: 10px"
            />
          </div>
        </el-form-item>

        <el-form-item label="媒体类型">
          <el-select
            v-model="cooperativeMediaForm.type"
            placeholder="请选择媒体类型"
          >
            <el-option label="报纸" value="newspaper" />
            <el-option label="杂志" value="magazine" />
            <el-option label="网络媒体" value="online" />
            <el-option label="电视" value="tv" />
            <el-option label="广播" value="radio" />
          </el-select>
        </el-form-item>

        <el-form-item label="媒体类型">
          <el-select
            v-model="cooperativeMediaForm.description"
            placeholder="请选择媒体类型"
          >
            <el-option label="大众媒体" value="大众媒体" />
            <el-option label="行业媒体" value="行业媒体" />
          </el-select>
        </el-form-item>

        <el-form-item label="官网链接">
          <el-input
            v-model="cooperativeMediaForm.website"
            placeholder="请输入官网链接"
          />
        </el-form-item>

        <el-form-item label="排序">
          <el-input-number v-model="cooperativeMediaForm.sort" :min="1" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="cooperativeMediaForm.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="cooperativeMediaDialogVisible = false"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="saveCooperativeMedia"
          :loading="saving"
          >保存</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { subpageApi as adminSubpageApi } from "@/api/admin";
import { subpageApi as siteSubpageApi } from "@/api/user";
import {
  Check,
  View,
  Edit,
  Plus,
  Search,
  Download,
  Upload,
} from "@element-plus/icons-vue";
import RichTextEditor from "@/components/RichTextEditor.vue";
import config from "@/config";
import CarouselManager from "@/components/admin/CarouselManager.vue";

export default {
  name: "AdminMedia",
  components: {
    Check,
    View,
    Edit,
    Plus,
    Search,
    RichTextEditor,
    CarouselManager,
  },
  setup() {
    const loading = ref(false);
    const saving = ref(false);
    const activeTab = ref("exhibition-news");
    const editDialogVisible = ref(false);
    const currentPageKey = ref("");
    const currentPageTitle = ref("");
    const tag = ref("");
    const isEditMode = ref(false);
    const editFormRef = ref(null);

    // 搜索和筛选
    const searchText = ref("");
    const statusFilter = ref("");

    // 合作媒体查询表单
    const cooperativeMediaQueryForm = reactive({
      name: "",
      type: "",
      status: "",
    });

    // 合作媒体编辑对话框
    const cooperativeMediaDialogVisible = ref(false);
    const cooperativeMediaDialogTitle = ref("");
    const cooperativeMediaForm = reactive({
      id: null,
      name: "",
      logo: "",
      type: "",
      description: "",
      website: "",
      sort: 1,
      status: "active",
    });
    const isCooperativeMediaEditMode = ref(false);

    // 页面数据存储 - 改为数组形式
    const pageData = reactive({
      "exhibition-news": [],
      "media-reports": [],
      "industry-news": [],
      "on-site-highlights": [],
      "cooperative-media": [],
    });

    // 编辑表单
    const editForm = reactive({
      id: null,
      title: "",
      subtitle: "",
      description: "",
      content: "",
      pageType: "",
      imageUrl: "",
      backgroundImage: "",
      videoUrl: "",
      linkUrl: "",
      sortOrder: 0,
      status: "active",
      isFeatured: false,
    });

    // 表单验证规则
    const editRules = reactive({
      title: [
        { required: true, message: "请输入页面标题", trigger: "blur" },
        {
          min: 2,
          max: 100,
          message: "标题长度在 2 到 100 个字符",
          trigger: "blur",
        },
      ],
      pageType: [
        { required: true, message: "请选择页面类型", trigger: "change" },
      ],
      content: [{ required: true, message: "请输入页面内容", trigger: "blur" }],
    });

    // 表单默认值
    const defaultForm = {
      id: null,
      title: "",
      subtitle: "",
      description: "",
      content: "",
      pageType: "",
      imageUrl: "",
      backgroundImage: "",
      videoUrl: "",
      linkUrl: "",
      sortOrder: 0,
      status: "active",
      isFeatured: false,
    };

    // 上传配置
    const apiConfig = config.getApiConfig();
    const uploadAction = ref(`${apiConfig.baseURL}/api/upload/image`);
    const videoUploadAction = ref(`${apiConfig.baseURL}/api/upload/video`);
    const uploadHeaders = ref({
      token: localStorage.getItem("adminToken") || "",
    });
    const videoUploading = ref(false);

    // 对话框标题
    const dialogTitle = computed(() => {
      return isEditMode.value
        ? `编辑${
            tag.value == "news"
              ? "资讯"
              : tag.value == "report"
              ? "报道"
              : "集锦"
          } - ${currentPageTitle.value}`
        : `新增${
            tag.value == "news"
              ? "资讯"
              : tag.value == "report"
              ? "报道"
              : "集锦"
          }`;
    });

    // 过滤后的合作媒体数据
    const filteredCooperativeMediaData = computed(() => {
      let data = pageData["cooperative-media"] || [];

      if (cooperativeMediaQueryForm.name) {
        data = data.filter(
          (item) =>
            item.title &&
            item.title
              .toLowerCase()
              .includes(cooperativeMediaQueryForm.name.toLowerCase())
        );
      }

      if (cooperativeMediaQueryForm.type) {
        data = data.filter((item) => {
          const content = getContentField(item, "type");
          return content === cooperativeMediaQueryForm.type;
        });
      }

      if (cooperativeMediaQueryForm.status) {
        data = data.filter(
          (item) => item.status === cooperativeMediaQueryForm.status
        );
      }

      return data;
    });

    // 获取页面数据列表（带搜索和筛选）
    const getPageList = (pageKey) => {
      let list = pageData[pageKey] || [];

      // 搜索筛选
      if (searchText.value) {
        const searchLower = searchText.value.toLowerCase();
        list = list.filter(
          (item) =>
            item.title.toLowerCase().includes(searchLower) ||
            getContentField(item, "description")
              .toLowerCase()
              .includes(searchLower) ||
            getContentField(item, "subtitle")
              .toLowerCase()
              .includes(searchLower)
        );
      }

      // 状态筛选
      if (statusFilter.value) {
        list = list.filter((item) => item.status === statusFilter.value);
      }

      return list;
    };

    // 获取页面数据（单个）
    const getPageData = (pageKey) => {
      return pageData[pageKey] || {};
    };

    // 获取content字段中的特定字段
    const getContentField = (row, field) => {
      if (!row.content) return "";

      // 如果content是纯文本，直接返回
      if (
        typeof row.content === "string" &&
        !row.content.trim().startsWith("{") &&
        !row.content.trim().startsWith("[")
      ) {
        // 如果是请求content字段本身，返回纯文本
        if (field === "content") {
          return row.content;
        }
        // 其他字段在纯文本情况下返回空
        return "";
      }

      try {
        const contentData =
          typeof row.content === "string"
            ? JSON.parse(row.content)
            : row.content;
        const value = contentData[field];
        // 对于布尔值，直接返回
        if (typeof value === "boolean") {
          return value;
        }
        // 对于字符串，返回字符串值
        return value || "";
      } catch (e) {
        // 如果JSON解析失败，说明是纯文本
        if (field === "content") {
          return row.content;
        }
        return "";
      }
    };

    // 加载所有页面数据
    const loadAllPageData = async () => {
      const pageKeys = [
        "exhibition-news",
        "media-reports",
        "industry-news",
        "on-site-highlights",
        "cooperative-media",
      ];

      for (const pageKey of pageKeys) {
        try {
          const response = await adminSubpageApi.getSubpageList(
            "media",
            pageKey
          );
          if (response && response.code === "200" && response.data) {
            pageData[pageKey] = response.data || [];
          } else {
            // 如果没有数据，使用模拟数据
            pageData[pageKey] = getMockData(pageKey);
          }
        } catch (error) {
          console.error(`加载${pageKey}数据失败:`, error);
          // 使用模拟数据
          pageData[pageKey] = getMockData(pageKey);
        }
      }
    };

    // 获取模拟数据
    const getMockData = (pageKey) => {
      const mockData = {
        "exhibition-news": [
          {
            id: 1,
            pageKey: "media",
            sectionKey: "exhibition-news",
            title: "2024年国际展览会盛大开幕",
            content: JSON.stringify({
              subtitle: "创新科技，引领未来",
              description: "展示最新的科技产品和创新解决方案",
              content:
                "<p>2024年国际展览会于今日盛大开幕，吸引了来自全球的参展商和观众...</p>",
              backgroundImage:
                "https://via.placeholder.com/400x300/3498DB/FFFFFF?text=News+BG",
              videoUrl: "",
              isFeatured: true,
            }),
            imageUrl:
              "https://via.placeholder.com/300x200/3498DB/FFFFFF?text=News",
            linkUrl: "",
            sortOrder: 1,
            status: "active",
            createdTime: "2024-01-15 10:00:00",
          },
        ],
        "media-reports": [
          {
            id: 2,
            pageKey: "media",
            sectionKey: "media-reports",
            title: "主流媒体关注展会盛况",
            content: JSON.stringify({
              subtitle: "媒体聚焦",
              description: "各大媒体对展会的报道",
              content: "<p>本次展会受到了各大主流媒体的广泛关注...</p>",
              backgroundImage:
                "https://via.placeholder.com/400x300/E74C3C/FFFFFF?text=Report+BG",
              videoUrl: "",
              isFeatured: false,
            }),
            imageUrl:
              "https://via.placeholder.com/300x200/E74C3C/FFFFFF?text=Report",
            linkUrl: "",
            sortOrder: 1,
            status: "active",
            createdTime: "2024-01-15 10:00:00",
          },
        ],
        "industry-news": [
          {
            id: 3,
            pageKey: "media",
            sectionKey: "industry-news",
            title: "行业发展趋势分析",
            content: JSON.stringify({
              subtitle: "行业洞察",
              description: "最新的行业发展趋势",
              content: "<p>根据最新数据分析，行业呈现以下发展趋势...</p>",
              backgroundImage:
                "https://via.placeholder.com/400x300/2ECC71/FFFFFF?text=Industry+BG",
              videoUrl: "",
              isFeatured: false,
            }),
            imageUrl:
              "https://via.placeholder.com/300x200/2ECC71/FFFFFF?text=Industry",
            linkUrl: "",
            sortOrder: 1,
            status: "active",
            createdTime: "2024-01-15 10:00:00",
          },
        ],
        "on-site-highlights": [
          {
            id: 4,
            pageKey: "media",
            sectionKey: "on-site-highlights",
            title: "展会现场精彩瞬间",
            content: JSON.stringify({
              subtitle: "精彩回顾",
              description: "展会现场的精彩瞬间",
              content:
                "<p>展会现场精彩纷呈，让我们回顾一下那些难忘的瞬间...</p>",
              backgroundImage:
                "https://via.placeholder.com/400x300/F39C12/FFFFFF?text=Highlights+BG",
              videoUrl: "",
              isFeatured: true,
            }),
            imageUrl:
              "https://via.placeholder.com/300x200/F39C12/FFFFFF?text=Highlights",
            linkUrl: "",
            sortOrder: 1,
            status: "active",
            createdTime: "2024-01-15 10:00:00",
          },
        ],
        "cooperative-media": [
          {
            id: 5,
            pageKey: "media",
            sectionKey: "cooperative-media",
            title: "合作媒体伙伴",
            content: JSON.stringify({
              subtitle: "媒体合作",
              description: "我们的合作媒体伙伴",
              content: "<p>感谢以下媒体伙伴的大力支持...</p>",
              backgroundImage:
                "https://via.placeholder.com/400x300/9B59B6/FFFFFF?text=Media+BG",
              videoUrl: "",
              isFeatured: false,
            }),
            imageUrl:
              "https://via.placeholder.com/300x200/9B59B6/FFFFFF?text=Media",
            linkUrl: "",
            sortOrder: 1,
            status: "active",
            createdTime: "2024-01-15 10:00:00",
          },
        ],
      };
      return mockData[pageKey] || [];
    };

    // 显示新增对话框
    const showAddDialog = (pageType, t) => {
      isEditMode.value = false;
      tag.value = t;
      currentPageKey.value = pageType;
      currentPageTitle.value = getPageTypeName(pageType);
      Object.assign(editForm, { ...defaultForm, pageType });
      editDialogVisible.value = true;
    };

    // 获取页面类型名称
    const getPageTypeName = (pageType) => {
      const typeNames = {
        "exhibition-news": "展会资讯",
        "media-reports": "媒体报道",
        "industry-news": "行业资讯",
        "on-site-highlights": "现场集锦",
        "cooperative-media": "合作媒体",
      };
      return typeNames[pageType] || pageType;
    };

    // 编辑页面项
    const editPageItem = (item, t) => {
      console.log(item, t);

      isEditMode.value = true;
      currentPageKey.value = item.pageType || activeTab.value;
      currentPageTitle.value =
        item.title || getPageTypeName(currentPageKey.value);

      // 解析content字段中的JSON数据
      let parsedContent = {};
      if (item.content) {
        try {
          parsedContent =
            typeof item.content === "string"
              ? JSON.parse(item.content)
              : item.content;
        } catch (e) {
          // 如果解析失败，将content作为纯文本处理
          parsedContent = { content: item.content };
        }
      }

      Object.assign(editForm, {
        id: item.id || null,
        title: item.title || "",
        subtitle: item.subtitle || parsedContent.subtitle || "",
        description: item.description || parsedContent.description || "",
        content: parsedContent.content || item.content || "",
        pageType: item.pageType || activeTab.value,
        imageUrl: item.imageUrl || parsedContent.imageUrl || "",
        backgroundImage:
          item.backgroundImage || parsedContent.backgroundImage || "",
        videoUrl: item.videoUrl || parsedContent.videoUrl || "",
        linkUrl: item.linkUrl || parsedContent.linkUrl || "",
        sortOrder: item.sortOrder || 0,
        status: item.status || "active",
        isFeatured: item.isFeatured || false,
      });

      editDialogVisible.value = true;
      tag.value = t;
    };

    // 删除页面项
    const deletePageItem = async (item) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除"${item.title}"吗？`,
          "确认删除",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        // 调用API删除
        if (item.id) {
          await adminSubpageApi.deleteSubpage(item.id);
        }

        // 从本地数据中移除
        const pageKey = item.pageType || activeTab.value;
        const index = pageData[pageKey].findIndex((p) => p.id === item.id);
        if (index > -1) {
          pageData[pageKey].splice(index, 1);
        }

        ElMessage.success("删除成功");
      } catch (error) {
        if (error !== "cancel") {
          ElMessage.error("删除失败: " + (error.message || "未知错误"));
        }
      }
    };

    // 保存页面内容
    const savePageContent = async () => {
      // 表单验证
      if (editFormRef.value) {
        const valid = await editFormRef.value.validate().catch(() => false);
        if (!valid) {
          ElMessage.error("请检查表单填写是否正确");
          return;
        }
      }

      saving.value = true;
      try {
        // 构建content字段的JSON数据
        const contentData = {
          content: editForm.content,
          subtitle: editForm.subtitle,
          description: editForm.description,
          backgroundImage: editForm.backgroundImage,
          videoUrl: editForm.videoUrl,
          isFeatured: editForm.isFeatured,
        };

        const formData = {
          pageKey: "media",
          sectionKey: isEditMode.value
            ? currentPageKey.value
            : editForm.pageType,
          title: editForm.title,
          content: JSON.stringify(contentData),
          imageUrl: editForm.imageUrl,
          linkUrl: editForm.linkUrl,
          sortOrder: editForm.sortOrder,
          status: editForm.status,
        };

        if (isEditMode.value && editForm.id) {
          formData.id = editForm.id;
          await adminSubpageApi.updateSubpage(formData);
        } else {
          await adminSubpageApi.addSubpage(formData);
        }

        // 更新本地数据
        const pageKey = editForm.pageType;
        const newItem = {
          ...formData,
          subtitle: editForm.subtitle,
          description: editForm.description,
          backgroundImage: editForm.backgroundImage,
          videoUrl: editForm.videoUrl,
          isFeatured: editForm.isFeatured,
          createdAt: isEditMode.value
            ? pageData[pageKey].find((item) => item.id === editForm.id)
                ?.createdAt || new Date().toISOString()
            : new Date().toISOString(),
        };

        if (isEditMode.value && editForm.id) {
          // 更新现有项
          const index = pageData[pageKey].findIndex(
            (item) => item.id === editForm.id
          );
          if (index > -1) {
            pageData[pageKey][index] = newItem;
          }
        } else {
          // 添加新项
          newItem.id = Date.now(); // 临时ID，实际应该从API返回
          pageData[pageKey].push(newItem);
        }

        editDialogVisible.value = false;
        ElMessage.success(isEditMode.value ? "更新成功" : "新增成功");

        // 重新加载数据以确保数据同步
        await loadAllPageData();
      } catch (error) {
        ElMessage.error("保存失败: " + (error.message || "未知错误"));
      } finally {
        saving.value = false;
      }
    };

    // 预览页面
    const previewPage = () => {
      if (editForm.title) {
        ElMessageBox.alert(
          `<h3>${editForm.title}</h3><p>${editForm.subtitle || ""}</p><div>${
            editForm.content
          }</div>`,
          "页面预览",
          {
            dangerouslyUseHTMLString: true,
            confirmButtonText: "关闭",
          }
        );
      } else {
        ElMessage.warning("请先填写页面标题");
      }
    };

    // 预览效果
    const handlePreview = () => {
      window.open("/media", "_blank");
    };

    // 关闭编辑对话框
    const handleCloseEditDialog = () => {
      editDialogVisible.value = false;
    };

    // 图片上传成功处理
    const handleImageSuccess = (response, field = "imageUrl") => {
      if (response && (response.code === "200" || response.code === 200)) {
        editForm[field] = response.data.url;
        ElMessage.success("图片上传成功!");
      } else {
        ElMessage.error("图片上传失败!");
      }
    };

    // 视频上传成功处理
    const handleVideoSuccess = (response) => {
      videoUploading.value = false;
      if (response && (response.code === "200" || response.code === 200)) {
        editForm.videoUrl = response.data.url;
        ElMessage.success("视频上传成功!");
      } else {
        ElMessage.error("视频上传失败!");
      }
    };

    // 视频上传前验证
    const beforeVideoUpload = (file) => {
      const isVideo = file.type.startsWith("video/");
      const isLt50M = file.size / 1024 / 1024 < 50;

      if (!isVideo) {
        ElMessage.error("只能上传视频文件!");
        return false;
      }
      if (!isLt50M) {
        ElMessage.error("视频大小不能超过 50MB!");
        return false;
      }
      videoUploading.value = true;
      return true;
    };

    // 图片上传前验证
    const beforeImageUpload = (file) => {
      const isImage = file.type.startsWith("image/");
      const isLt5M = file.size / 1024 / 1024 < 15;

      if (!isImage) {
        ElMessage.error("只能上传图片文件!");
        return false;
      }
      if (!isLt5M) {
        ElMessage.error("图片大小不能超过 15MB!");
        return false;
      }
      return true;
    };

    // 重置表单
    const resetForm = () => {
      Object.assign(editForm, { ...defaultForm, pageType: editForm.pageType });
    };

    // 搜索处理
    const handleSearch = () => {
      // 搜索逻辑已在getPageList中实现
    };

    // 筛选处理
    const handleFilter = () => {
      // 筛选逻辑已在getPageList中实现
    };

    // 合作媒体查询方法
    const searchCooperativeMediaData = () => {
      // 查询逻辑已在computed中实现，这里可以添加额外的查询逻辑
      ElMessage.success("查询完成");
    };

    const resetCooperativeMediaQuery = () => {
      Object.assign(cooperativeMediaQueryForm, {
        name: "",
        type: "",
        status: "",
      });
      ElMessage.info("查询条件已重置");
    };

    // 合作媒体模板下载
    const downloadCooperativeMediaTemplate = () => {
      // 创建CSV模板，字段顺序与后端API匹配
      const headers = [
        "媒体名称",
        "媒体类型",
        "媒体描述",
        "Logo链接",
        "官网链接",
        "排序",
      ];
      const template = [
        headers,
        [
          "# 注意：媒体名称和Logo链接不能重复，重复数据将被跳过",
          "",
          "",
          "",
          "",
          "",
        ],
        [
          "# 媒体类型可选值：newspaper(报纸)、tv(电视)、online(网络)、magazine(杂志)",
          "",
          "",
          "",
          "",
          "",
        ],
        [
          "示例媒体1",
          "newspaper",
          "权威财经媒体",
          "https://example.com/logo1.png",
          "https://example.com",
          "1",
        ],
        [
          "示例媒体2",
          "tv",
          "知名电视台",
          "https://example.com/logo2.png",
          "https://tv-example.com",
          "2",
        ],
        [
          "示例媒体3",
          "online",
          "网络媒体平台",
          "",
          "https://online-example.com",
          "3",
        ],
        [
          "示例媒体4",
          "magazine",
          "专业杂志",
          "https://example.com/logo4.png",
          "",
          "4",
        ],
      ];

      // 转换为CSV格式，正确处理包含逗号的字段
      const csvContent = template
        .map((row) =>
          row
            .map((cell) => {
              // 如果字段包含逗号、引号或换行符，需要用引号包围
              if (
                cell.includes(",") ||
                cell.includes('"') ||
                cell.includes("\n")
              ) {
                return `"${cell.replace(/"/g, '""')}"`;
              }
              return cell;
            })
            .join(",")
        )
        .join("\n");

      const blob = new Blob(["\ufeff" + csvContent], {
        type: "text/csv;charset=utf-8;",
      });
      const link = document.createElement("a");
      const url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", "合作媒体导入模板.csv");
      link.style.visibility = "hidden";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      ElMessage.success("模板下载成功");
    };

    // 触发合作媒体批量导入
    const cooperativeMediaImportRef = ref(null);
    const triggerCooperativeMediaImport = () => {
      cooperativeMediaImportRef.value?.click();
    };

    // 处理合作媒体批量导入
    const handleCooperativeMediaImport = async (event) => {
      const file = event.target.files[0];
      if (!file) return;

      try {
        loading.value = true;
        ElMessage.info("正在导入合作媒体数据...");

        const formData = new FormData();
        formData.append("file", file);
        formData.append("type", "cooperative-media");

        const apiConfig = config.getApiConfig();
        const response = await fetch(
          `${apiConfig.baseURL}/admin/subpage/cooperative-media/import`,
          {
            method: "POST",
            headers: {
              token: localStorage.getItem("adminToken") || "",
            },
            body: formData,
          }
        );

        const result = await response.json();
        if (result && (result.code === "200" || result.code === 200)) {
          const successCount = result.data?.successCount || 0;
          const errorCount = result.data?.errorCount || 0;
          const errorMessages = result.data?.errorMessages || "";

          if (successCount > 0) {
            let message = `批量导入完成！成功导入 ${successCount} 条数据`;
            if (errorCount > 0) {
              message += `，跳过 ${errorCount} 条重复或无效数据`;
            }
            ElMessage.success(message);

            // 如果有错误信息，显示详细信息
            if (errorMessages) {
              console.log("导入详细信息:", errorMessages);
              ElMessageBox.alert(errorMessages, "导入详情", {
                confirmButtonText: "确定",
                type: "warning",
                customClass: "import-detail-dialog",
              });
            }
          } else {
            ElMessage.warning("没有新数据被导入，所有数据都已存在或格式错误");
          }

          // 重新加载合作媒体数据
          await loadAllPageData();
        } else {
          ElMessage.error(result?.message || "批量导入失败");
        }
      } catch (error) {
        console.error("导入失败:", error);
        ElMessage.error("导入失败，请检查文件格式");
      } finally {
        loading.value = false;
        // 清空文件选择
        if (cooperativeMediaImportRef.value) {
          cooperativeMediaImportRef.value.value = "";
        }
      }
    };

    // 新增合作媒体
    const addCooperativeMedia = () => {
      isCooperativeMediaEditMode.value = false;
      cooperativeMediaDialogTitle.value = "新增合作媒体";
      Object.assign(cooperativeMediaForm, {
        id: null,
        name: "",
        logo: "",
        type: "",
        description: "",
        website: "",
        sort: (pageData["cooperative-media"]?.length || 0) + 1,
        status: "active",
      });
      cooperativeMediaDialogVisible.value = true;
    };

    // 编辑合作媒体
    const editCooperativeMedia = (row) => {
      isCooperativeMediaEditMode.value = true;
      cooperativeMediaDialogTitle.value = "编辑合作媒体";

      // 解析content字段
      let parsedContent = {};
      if (row.content) {
        try {
          parsedContent =
            typeof row.content === "string"
              ? JSON.parse(row.content)
              : row.content;
        } catch (e) {
          parsedContent = {};
        }
      }

      Object.assign(cooperativeMediaForm, {
        id: row.id,
        name: row.title || "",
        logo: row.imageUrl || "",
        type: parsedContent.type || "",
        description: parsedContent.description || "",
        website: row.linkUrl || "",
        sort: row.sortOrder || 1,
        status: row.status || "active",
      });
      cooperativeMediaDialogVisible.value = true;
    };

    // 删除合作媒体
    const deleteCooperativeMedia = async (index) => {
      try {
        await ElMessageBox.confirm("确定要删除这个合作媒体吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        const item = pageData["cooperative-media"][index];
        if (item && item.id) {
          await adminSubpageApi.deleteSubpage(item.id);
        }

        pageData["cooperative-media"].splice(index, 1);
        ElMessage.success("删除成功");
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除失败:", error);
          ElMessage.error("删除失败");
        }
      }
    };

    // 切换合作媒体状态
    const toggleCooperativeMediaStatus = (row) => {
      row.status = row.status === "active" ? "inactive" : "active";
      ElMessage.success("状态更新成功");
    };

    // 保存合作媒体
    const saveCooperativeMedia = async () => {
      try {
        saving.value = true;

        const formData = {
          pageKey: "media",
          sectionKey: "cooperative-media",
          title: cooperativeMediaForm.name,
          content: JSON.stringify({
            type: cooperativeMediaForm.type,
            description: cooperativeMediaForm.description,
          }),
          imageUrl: cooperativeMediaForm.logo,
          linkUrl: cooperativeMediaForm.website,
          sortOrder: cooperativeMediaForm.sort,
          status: cooperativeMediaForm.status,
        };

        let response;
        if (isCooperativeMediaEditMode.value && cooperativeMediaForm.id) {
          formData.id = cooperativeMediaForm.id;
          response = await adminSubpageApi.updateSubpage(formData);
        } else {
          response = await adminSubpageApi.addSubpage(formData);
        }

        if (response && response.code === "200") {
          ElMessage.success(
            isCooperativeMediaEditMode.value ? "更新成功" : "添加成功"
          );
          cooperativeMediaDialogVisible.value = false;
          loadAllPageData(); // 重新加载数据
        } else {
          ElMessage.error(response?.msg || "保存失败");
        }
      } catch (error) {
        console.error("保存失败:", error);
        ElMessage.error("保存失败");
      } finally {
        saving.value = false;
      }
    };

    // 合作媒体图片上传成功处理
    const handleCooperativeMediaImageSuccess = (response, field) => {
      if (response && (response.code === "200" || response.code === 200)) {
        cooperativeMediaForm[field] = response.data.url;
        ElMessage.success("图片上传成功!");
      } else {
        ElMessage.error("图片上传失败!");
      }
    };

    // 预览图片
    const previewImages = (row) => {
      const images = [];
      if (row.imageUrl) {
        images.push(row.imageUrl);
      }
      const backgroundImage = getContentField(row, "backgroundImage");
      if (backgroundImage) {
        images.push(backgroundImage);
      }

      if (images.length > 0) {
        ElMessageBox.alert(
          `<div style="text-align: center;">
            ${images
              .map(
                (img) =>
                  `<img src="${img}" style="max-width: 100%; max-height: 400px; margin: 10px; border-radius: 8px;" />`
              )
              .join("")}
          </div>`,
          `图片预览 - ${row.title}`,
          {
            dangerouslyUseHTMLString: true,
            confirmButtonText: "关闭",
            customClass: "image-preview-dialog",
          }
        );
      }
    };

    // 预览内容
    const previewContent = (row) => {
      const content = getContentField(row, "content");
      if (content) {
        ElMessageBox.alert(content, `预览内容 - ${row.title}`, {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "关闭",
          customClass: "content-preview-dialog",
        });
      } else {
        ElMessage.info("暂无内容可预览");
      }
    };

    // 去除HTML标签
    const stripHtml = (html) => {
      if (!html) return "";
      const tmp = document.createElement("div");
      tmp.innerHTML = html;
      return tmp.textContent || tmp.innerText || "";
    };

    onMounted(() => {
      loadAllPageData();
    });

    return {
      loading,
      saving,
      activeTab,
      editDialogVisible,
      currentPageKey,
      currentPageTitle,
      isEditMode,
      editFormRef,
      searchText,
      statusFilter,
      cooperativeMediaQueryForm,
      filteredCooperativeMediaData,
      cooperativeMediaDialogVisible,
      cooperativeMediaDialogTitle,
      cooperativeMediaForm,
      isCooperativeMediaEditMode,
      pageData,
      editForm,
      editRules,
      defaultForm,
      uploadAction,
      videoUploadAction,
      uploadHeaders,
      videoUploading,
      dialogTitle,
      tag,
      getPageList,
      getPageData,
      getContentField,
      loadAllPageData,
      getMockData,
      showAddDialog,
      getPageTypeName,
      editPageItem,
      deletePageItem,
      savePageContent,
      previewPage,
      handlePreview,
      handleCloseEditDialog,
      handleImageSuccess,
      handleVideoSuccess,
      beforeImageUpload,
      beforeVideoUpload,
      resetForm,
      handleSearch,
      handleFilter,
      searchCooperativeMediaData,
      resetCooperativeMediaQuery,
      downloadCooperativeMediaTemplate,
      triggerCooperativeMediaImport,
      handleCooperativeMediaImport,
      cooperativeMediaImportRef,
      addCooperativeMedia,
      editCooperativeMedia,
      deleteCooperativeMedia,
      toggleCooperativeMediaStatus,
      saveCooperativeMedia,
      handleCooperativeMediaImageSuccess,
      previewImages,
      previewContent,
      stripHtml,
    };
  },
};
</script>

<style scoped>
.admin-media {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.content-tabs {
  margin-top: 20px;
}

.tab-content {
  padding: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.list-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.list-header .header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.content-preview {
  cursor: pointer;
  color: #409eff;
  text-decoration: underline;
}

.content-preview:hover {
  color: #66b1ff;
}

.image-container {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.table-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  color: #909399;
  font-size: 12px;
}

.edit-dialog {
  max-width: 1200px;
}

.edit-content {
  max-height: 70vh;
  overflow-y: auto;
}

.image-upload-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-uploader:hover {
  border-color: #409eff;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.image-preview-dialog) {
  max-width: 80vw;
}

:deep(.content-preview-dialog) {
  max-width: 60vw;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .list-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .list-header .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

/* 查询表单样式 */
.query-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
}

.query-form .el-form-item {
  margin-bottom: 0;
}

/* 导入详情对话框样式 */
:deep(.import-detail-dialog) {
  .el-message-box__content {
    max-height: 300px;
    overflow-y: auto;
    white-space: pre-line;
    font-family: monospace;
    font-size: 12px;
    line-height: 1.5;
    background: #f5f5f5;
    padding: 15px;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
  }
}
</style>
